package top.lunarye.handler.receiver;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import top.lunarye.common.domaim.TaskInfo;
import top.lunarye.handler.pending.Task;
import top.lunarye.handler.pending.TaskPendingHolder;
import top.lunarye.handler.utils.GroupIdMappingUtils;

import javax.annotation.Resource;

/**
 * 消费MQ的消息
 * @author lunar
 * @since 2022-07-18
 */
@Slf4j
@Component
// 设置每次调用的时候都会生成一个新的实例
//@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RocketMQMessageListener(topic = "#{'${message.business.topic.name}'}", consumerGroup = "consumer-group")
public class Receiver implements RocketMQListener<String> {

    @Resource
    private ApplicationContext context;

    @Resource
    private TaskPendingHolder taskPendingHolder;


    @Override
    public void onMessage(String message) {
        var taskInfoLists = JSON.parseArray(message, TaskInfo.class);

        String messageGroupId = GroupIdMappingUtils.getGroupIdByTaskInfo(CollUtil.getFirst(taskInfoLists.iterator()));

        for (TaskInfo taskInfo : taskInfoLists) {
            Task task = context.getBean(Task.class).setTaskInfo(taskInfo);
            // 先获得当前消息发送种类所属的线程池，然后再将任务提交到线程池
            taskPendingHolder.route(messageGroupId).execute(task);
        }
    }
}
